<?php

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;
use think\exception\HttpResponseException;

/**
 * 销售管理
 */
class Sales extends BasicAdmin
{

    /**
     * 定义当前操作表名
     * @var string
     */
    public $sales = 'tp_sales';
    public $cate = 'tp_vote_cate';

    /**
     * 列表
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {

        $get = $this->request->get();
        $db = Db::name($this->sales)
            ->alias('a')
            ->field('a.*');

        foreach (['name', 'mobile', 'supermarket', 'jxs','shop'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $value = trim($get[$field]);
                $db->whereLike('a.' . $field, "%{$value}%");
            }
        }
        foreach (['is_reg'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $value = trim($get[$field]);
                $db->where('a.' . $field, "{$value}");
            }
        }

        $cates = Db::name($this->cate)
            ->field('cate_id,name')
            ->where('pid', 0)
            ->order('sort desc')
            ->select();
        $this->assign('cates', $cates);

        $sessin_user = session('user');
        if ($sessin_user['cate_id'] > 0) {
            $db = $db->where(['a.cate_id' => $sessin_user['cate_id']]);
        }

        return parent::_list($db->order('a.sales_id desc'), 'sales_id');
    }

    //导出数据
    public function outItems()
    {
        $get = input();

        $db = Db::name($this->sales)
            ->alias('a')
            ->field('a.sales_id,a.cate_name,a.jxs,a.supermarket,a.name,a.mobile,a.shop,a.is_reg');

        foreach (['name', 'mobile', 'supermarket', 'jxs','shop'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $value = trim($get[$field]);
                $db->whereLike('a.' . $field, "%{$value}%");
            }
        }
        foreach (['is_reg'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $value = trim($get[$field]);
                $db->where('a.' . $field, "{$value}");
            }
        }

        $title = '全部';

        $db->where([]);
        $db->order('a.sales_id desc');
        $data = $db->select();

        $reg = array(
            '0' => '未报名',
            '1' => '已报名',
        );

        $newData = array();
        foreach ($data as $one) {
            $one['is_reg'] = $reg[$one['is_reg']];
            $newData[] = $one;
        }
        $header = array('ID', '赛区', '经销商', '商超系统', '姓名', '手机号', '门店', '报名状态');
        $name = $title . '数据';
        $result = \classes\Excel::writer($header, $newData, $name);

        if ($result) {
            $this->success('导出成功');
        } else {
            $this->error('导出失败');
        }

    }

    /**
     * 添加
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add_bak()
    {
        $cates = Db::name($this->cate)
            ->field('cate_id,name')
            ->where('pid', 0)
            ->order('sort desc')
            ->select();

        $sessin_user = session('user');
        $this->assign('cate_id', $sessin_user['cate_id']);
        $this->assign('cates', $cates);

        return $this->_form($this->sales, 'form');
    }

    /**
     * 添加
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        if (!$this->request->isPost()) {

            $cates = Db::name($this->cate)
                ->field('cate_id,name')
                ->where('pid', 0)
                ->order('sort desc')
                ->select();

            $sessin_user = session('user');

            return $this->fetch('form', ['cates' => $cates, 'cate_id' => $sessin_user['cate_id']]);
        }
        try {
            $data = $this->request->post();
            $cate = Db::name($this->cate)->where(['cate_id' => $data['cate_id']])->find();
            $data['cate_name'] = $cate['name'];

            Db::transaction(function () use ($data) {
                Db::name($this->sales)->insert($data);
            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('添加失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('添加成功！', "");
    }

    /**
     * 编辑
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get('id');

            $cates = Db::name($this->cate)
                ->field('cate_id,name')
                ->where('pid', 0)
                ->order('sort desc')
                ->select();

            $sessin_user = session('user');

            $query = Db::name($this->sales)->where(['sales_id' => $id])->find();
            empty($query) && $this->error('需要编辑的不存在！');
            return $this->fetch('form', ['vo' => $query, 'cates' => $cates, 'cate_id' => $sessin_user['cate_id'], 'title' => '编辑']);
        }
        try {
            $id = $this->request->post('id');
            $data = $this->request->post();
            $query = Db::name($this->sales)->where(['sales_id' => $id])->find();
            $cate = Db::name($this->cate)->where(['cate_id' => $data['cate_id']])->find();
            $data['cate_name'] = $cate['name'];
            empty($query) && $this->error('编辑失败，请稍候再试！');

            Db::transaction(function () use ($data, $id, $query) {
                $where = ['sales_id' => $id];
                Db::name($this->sales)->where($where)->update($data);

            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('编辑失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('编辑成功！', "");
    }

    /**
     * 删除
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        if (DataService::update($this->sales)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

}
